package com.example.yc.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * JSON和LIST之间转换
 * List<object> to List<String>
 */
public class JsonUtil {
    public static String listToJSONObject(List<HashMap<String, String>>list	){
        JSONArray jsonArray=new JSONArray();
        for(HashMap<String, String>HashMap:list){
            JSONObject jsonObject=new JSONObject();
            for(String key:HashMap.keySet()){
                jsonObject.put(key, HashMap.get(key));
            }
            jsonArray.add(jsonObject);
        }
        return jsonArray.toJSONString();
    }

    public static List<HashMap<String, String>> JSONtoList(String data){
        List<HashMap<String, String>> list2=new ArrayList<>();
        JSONArray jsonArray= JSON.parseArray(data);
        for(int i=0;i<jsonArray.size();i++){
            HashMap<String, String>HashMap=new HashMap<>();
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            Set<String> set=jsonObject.keySet();
            for(String key:set){
                HashMap.put(key, jsonObject.getString(key));
            }
            list2.add(HashMap);
        }
        return list2;
    }

    public static List<String> ListHashMapToListString(List<HashMap<String,String>> lm){
        List<String> ls = new ArrayList<>();
        for(HashMap<String,String> hm : lm){
            ls.add(JSON.toJSONString(hm));
        }
        return ls;
    }
}
